<template>
  <div class='container'>
    <div class="main">
      <div class="entering">
        试题录入
      </div>
      <div class="test-from">
      <!-- 学科-难度 -->
      <el-form
        :model="Questions"
        label-width="150px"
        ref="corporateForm"
        class="adduser-container"
        :rules="rules"
      >
        <div>
          <el-form-item
            label="学科:"
            prop="subjectID"
          >
            <el-select
              style="width: 40%"
              v-model="Questions.subjectID"
              placeholder="请选择"
            >
              <el-option
                v-for="(item, i) in simpleList"
                :key="i"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item
            label="目录:"
            prop="catalogID"
          >
            <el-select
              style="width: 40%"
              v-model="Questions.catalogID"
              placeholder="请选择"
            >
              <el-option
                v-for="(item, i) in catalogueslist"
                :key="i"
                :label="item.label"
                :value="item.value"
              >
                {{  item.label }}
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item
            label="企业:"
            prop="enterpriseID"
          >
            <el-select
              style="width: 40%"
              v-model="Questions.enterpriseID"
              placeholder="请选择"
            >
              <el-option
                v-for="(item, i) in companyslist.items"
                :key="i"
                :label="item.company"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item
            label="城市:"
            prop="province"
            style="width: 50%"
          >
            <div class="city-select">
              <div>
                <el-select
                  v-model="Questions.province"
                  placeholder="请选择"
                  @change="changeCity"
                >
                  <el-option
                    v-for="(item, i) in cityslist(citydatas)"
                    :key="i"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </div>
              <div>
                <el-select
                  v-model="Questions.city"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, i) in district(Questions.province,citydatas)"
                    :key="i"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </div>
            </div>
          </el-form-item>
        </div>
        <div>
          <el-form-item
            label="方向:"
            prop="direction"
          >
            <el-select
              v-model="Questions.direction"
              style="width: 40%"
              placeholder="请选择"
            >
              <el-option
                v-for="(item, i) in direction"
                :key="i"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item
            label="题型:"
            prop="questionType"
          >
            <template>
              <el-radio
                v-model="Questions.questionType"
                label="1"
              >
                单选
              </el-radio>
              <el-radio
                v-model="Questions.questionType"
                label="2"
              >
                多选
              </el-radio>
              <el-radio
                v-model="Questions.questionType"
                label="3"
              >
                简答
              </el-radio>
            </template>
          </el-form-item>
        </div>
        <div>
          <el-form-item
            label="难度:"
            prop="difficulty"
          >
            <el-radio
              v-model="Questions.difficulty"
              label="1"
            >
              简单
            </el-radio>
            <el-radio
              v-model="Questions.difficulty"
              label="2"
            >
              一般
            </el-radio>
            <el-radio
              v-model="Questions.difficulty"
              label="3"
            >
              困难
            </el-radio>
          </el-form-item>
        </div>
        <!-- 题干 -->
        <div>
          <el-form-item
            label="题干:"
            prop="question"
            style="width: 90%"
          >
            <quill-editor
              v-model="Questions.question"
              :options="editorOption"
            >
            </quill-editor>
          </el-form-item>
        </div>
        <!-- 单选 -->
        <div
          class="options"
          v-show="Questions.questionType !== '2' && Questions.questionType !== '3'"
        >
          <el-form-item
            label="选项:"
          >
            <div
              class="result"
              v-for="(item, i) in Questions.options"
              :key="i"
            >
              <div>
                <el-radio
                  :label="item.code"
                  v-model="radioResult"
                >
                  {{ item.code + ':' }}
                </el-radio>
              </div>
              <div>
                <el-input
                  class="input"
                  v-model="Questions.options[i].title"
                  @input.native="changeOption($event,i)"
                />
              </div>
              <div>
                <el-badge value="x" class="item">
                  <el-upload
                    action="https://jsonplaceholder.typicode.com/posts/"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove">
                    <div class="update-picture">上传图片</div>
                  </el-upload>
                </el-badge>
              </div>
            </div>
            <div>
              <el-button
                type="danger"
                disabled
                size="small"
                class="add-option"
              >
                +增加选项于答案
              </el-button>
            </div>
          </el-form-item>
        </div>
        <!-- 多选 -->
        <div
        class="options"
        v-show="Questions.questionType !== '1' && Questions.questionType !== '3'"
      >
        <el-form :model="Questions" label-width="150px">
          <el-form-item
            label="选项:"
            style="width: 50%"
          >
            <div
              class="result"
              v-for="(item, i) in checkBox"
              :key="i"
            >
              <div>
                <el-checkbox
                  v-model="Questions.options[i].isRight"
                  :label="item"
                >
                  {{ item + ':' }}
                </el-checkbox>
              </div>
              <div>
                <el-input
                  class="input"
                  v-model="Questions.options[i].title"
                  @input.native="changeOptionchecked($event,i)"
                />
              </div>
              <div>
                <el-badge
                  value="x"
                  class="item"
                  @click.native="handleRemove"
                >
                  <el-upload
                    action="https://jsonplaceholder.typicode.com/posts/"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove">
                    <div class="update-picture">上传图片</div>
                  </el-upload>
                </el-badge>
              </div>
            </div>
            <div>
              <el-button
                type="danger"
                size="small"
                class="add-option"
                @click="addOption"
              >
                +增加选项于答案
              </el-button>
            </div>
          </el-form-item>
        </el-form>
        </div>
        <!-- 视频解析 -->
        <div class="options">
          <el-form-item
            label="视频解析:"
            prop="videoURL"

          >
          <el-input
            style="width: 40%"
            placeholder="根据题干搜索"
            v-model="Questions.videoURL"
          />
          </el-form-item>
        </div>
        <!-- 答案解析 -->
        <div>
            <el-form-item
              label="答案解析:"
              style="width: 90%"
              prop="answer"
            >
              <quill-editor
                  v-model="Questions.answer"
                  ref="myQuillEditor"
                  :options="editorOption"
                >
              </quill-editor>
            </el-form-item>
        </div>
      </el-form>
      </div>
      <!-- 题目备注 -->
      <div class="options">
        <el-form
          label-width="150px"
          class="adduser-container"
          :model="Questions"
        >
          <el-form-item
            label="题目备注:"
            prop="remarks"
            style="width: 50%"
          >
            <el-input
              type="textarea"
              :rows="2"
              v-model="Questions.remarks"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="试题标签:"
            prop="tags"
          >
            <el-select
              style="width: 40%"
              v-model="Questions.tags"
              multiple
              filterable
              placeholder="请选择试题标签">
              <el-option
                v-for="(item, i) in direction"
                :key="i"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              v-if="!this.$route.query.id"
              type="primary"
              @click="submit"
            >
              确认提交
            </el-button>
            <el-button
              v-if="this.$route.query.id"
              type="success"
              @click="editOk"
            >
              确认修改
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
// 引入富文本
import VueQuillEditor from 'vue-quill-editor'
import 'quill/dist/quill.snow.css'

import { mapState, mapActions } from 'vuex'
import { datas, provinces, citys } from '@/api/hmmm/citys'
import * as catalogues from '@/api/hmmm/citys'
import * as constants from '@/api/hmmm/constants'
import * as questions from '@/api/hmmm/questions'
export default {
  name: 'questionsNew',
  components: {
    VueQuillEditor
  },
  data() {
    // 学科
    const validateSubjectID = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('请选择学科')))
      } else {
        callback()
      }
    }
    // 目录
    const validateCatalogID = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('请选择目录')))
      } else {
        callback()
      }
    }
    // 企业
    const validateEnterpriseID = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('请选择企业')))
      } else {
        callback()
      }
    }
    // 城市
    const validateProvince = (rule, value, callback) => {
      if (value === '') {
        console.log('11111111',value);
        callback(new Error(this.$t('请选择城市')))
      } else {
        callback()
      }
    }
    // 方向
    const validateDirection = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('请选择方向')))
      } else {
        callback()
      }
    }
    // 题型
    const validateQuestionType = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('请选择题型')))
      } else {
        callback()
      }
    }
    // 难度
    const validateDifficulty = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('请选择难度')))
      } else {
        callback()
      }
    }
    // 题干
    const validateQuestion = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('请选择题干')))
      } else {
        callback()
      }
    }
    // 答案解析
    const validateAnswer = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('请输入答案解析')))
      } else {
        callback()
      }
    }
    return {
      labelWidth: '150px',
      // 城市区域函数
      district: citys,
      // 城市函数
      cityslist: provinces,
      // 城市数据
      citydatas: datas,
      // 试题录入方向
      direction: constants.direction,
      // 试题录入值
      Questions: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        options: [
          { isRight: true, code: 'A', title: '', img: '',},
          { isRight: false, code: 'B', title: '', img: '',},
          { isRight: false, code: 'C', title: '', img: '',},
          { isRight: false, code: 'D', title: '', img: '',}
        ],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: [],
      },
      // 单选框选中的值
      radio: ['A', 'B', 'C', 'D'],
      // 复选框选中的值
      checkBox: ['A', 'B', 'C', 'D'],
      // A到Z的数组
      letter: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
      // 答案单选项
      radioResult: 'A',
      textarea: '',
      catalogues: catalogues.simple,
      notice: {
        content: ''
      },
      rules: {
        // 学科
        subjectID: [
          { required: true, trigger: 'blur' , validator: validateSubjectID },
        ],
        // 目录
        catalogID: [
          { required: true, trigger: 'blur' , validator: validateCatalogID},
        ],
        // 企业
        enterpriseID: [
          { required: true, trigger: 'blur' , validator: validateEnterpriseID},
        ],
        // 城市
        province: [
          { required: true, trigger: 'blur' , validator: validateProvince},
        ],
        // 方向
        direction: [
          { required: true, trigger: 'blur' , validator: validateDirection},
        ],
        // 题型
        questionType: [
          { required: true, trigger: 'blur' , validator: validateQuestionType},
        ],
        // 难度
        difficulty: [
          { required: true, trigger: 'blur' , validator: validateDifficulty},
        ],
        // 题干
        question: [
          { required: true, trigger: 'blur' , validator: validateQuestion},
        ],
        // 答案解析
        answer: [
          { required: true, trigger: 'blur' , validator: validateAnswer},
        ],
      },
      editorOption: {
        placeholder: '',
        modules: {
        toolbar: [
          ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线s
          [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
          ['blockquote', 'code-block'],// 代码块
          ['image', 'link'] // 链接、图片、视频
          ]
        },
      },
    }
  },
  created() {
    // 目录
    this.uptatecatalogueslist()
    this.getSimpleList()
    this.uptateCompanysList({
      page: 1,
      pagesize: 1000
    })
    console.log(this.$route.query.id);
    if (this.$route.query.id) {
      this.uptateDetail({
        id: this.$route.query.id
      })
      .then(() => {
        this.Questions.subjectID = this.detail.subjectID
        this.Questions.catalogID = this.detail.catalogID
        this.Questions.enterpriseID = this.detail.enterpriseID
        this.Questions.province = this.detail.province
        this.Questions.city = this.detail.city
        this.Questions.direction = this.detail.direction
        this.Questions.questionType = this.detail.questionType
        this.Questions.difficulty = this.detail.difficulty
        this.Questions.question = this.detail.question
        this.Questions.options = this.detail.options
        this.Questions.videoURL = this.detail.videoURL
        this.Questions.answer = this.detail.answer
        this.Questions.remarks = this.detail.remarks
        this.Questions.id = this.detail.id
        if (this.detail.tags) {
          this.Questions.tags.push(this.detail.tags)
        }
      })
    }

  },
  computed: {
    // 简单学科列表
    ...mapState('subjects', [
        'simpleList'
      ]),
    // 简单目录列表
    ...mapState('directorys', [
      'catalogueslist'
    ]),
    // 企业列表
    ...mapState('companys',  [
      'companyslist'
    ]),
    // 试题列表
    ...mapState('questions', [
      'detail'
      ]),
  },
  methods: {
    // 简单学科列表
    ...mapActions('subjects', [
      'getSimpleList'
    ]),
    // 简单目录列表
    ...mapActions('directorys', [
      'uptatecatalogueslist'
    ]),
    // 企业列表
    ...mapActions('companys', [
      'uptateCompanysList'
    ]),
    // 试题列表
    ...mapActions('questions', [
      'uptateDetail'
    ]),
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // 试题录入城市select
    changeCity(val) {
      this.district(val,this.citydatas);
      // 区域反显
      const transition = this.district(val,this.citydatas)[0];
      this.Questions.city = transition;
    },
    // 单选输入框选中的值
    changeOption(e,index) {
      this.Questions.options[index].isRight = true;
    },
    // 复选输入框选中的值
    changeOptionchecked(index) {

    },
    // 增加选项于答案
    addOption() {
      const end = this.checkBox.find(d => d === 'Z')
      if (end) {
        this.$message.error('最多只能添加26个选项')
      } else {
        this.checkBox.push(this.letter[this.checkBox.length])
        this.Questions.options.push({
          isRight: false,
          code: this.letter[this.checkBox.length],
          title: '',
          img: '',
        })
      }
    },
    // 确认添加试题
    submit() {
      const data = this.Questions
      for (const key in data) {
        if (data[key] === '') {
          delete data[key]
        }
      }
      this.$refs.corporateForm.validate((valid) => {
        if (valid) {
          questions.addquestions(data)
          .then(() => {
            this.$message.success('添加成功')
          })
          .catch(() => {
            this.$message.error('添加失败')
          })
        }
      })
      // questions.addquestions(data)
      //   .then(() => {
      //     this.$message.success('添加成功')
      //   })
      //   .catch(() => {
      //     this.$message.error('添加失败')
      //   })
    },
    // 确认修改试题
    editOk() {
      questions.updateQuestions(this.Questions)
        .then(() => {
          this.$message.success('修改成功')
          this.$router.go(-1)
        })
        .catch(() => {
          this.$message.error('修改失败')
        })
    },
    // 删除选项于答案
    handleRemove() {
      // 从最后一个开始删除
      const end = this.checkBox.length
      if (end === 4) {
        // this.$message.error('禁止删除默认选项')
        return
      } else {
        this.checkBox.splice(this.checkBox.length - 1, 1)
      }
      // this.checkBox.splice(this.checkBox.length - 1, 1)
    }
  }
}
</script>

<style scoped lang='scss'>
.container {
  padding: 16px;

  .main {
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding-bottom: 16px;

    .entering {
      padding: 16px;
      border-bottom: 1px solid #edf0f6;
      margin-bottom: 16px;
    }

    .test-from {
      // width: 50%;
      // 城市选择
      .city-select {
        // grid布局
        display: grid;
        grid-template-columns: repeat(2, 50%);
        // 中间有空隙
        grid-gap: 5px;
        padding-right: 5px;
        overflow: hidden;
      }

      .select-input {
        width: 100%;
      }

    }

    .options {
      // width: 50%;

      .result {
        display: flex;
        width: 290px;
        align-items: center;
        margin-top: 16px;

        .input {
          flex: 1;
          padding: 0 4px;
        }
      }

      .add-option {
        margin-top: 16px;
      }

      .select-input {
        width: 50px;
      }
    }

  }
}
// 富文本框
// ::v-deep .ql-toolbar.ql-snow {
//   width: calc(100vw - 16px);
// }
// // 富文本框
::v-deep .ql-toolbar.ql-snow + .ql-container.ql-snow {
  height: 200px;
}
// 上传图片
::v-deep .el-upload--picture-card {
  width: 100px;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;

  .update-picture {
    font-size: 12px;
    color:black;
    font-style: normal;
  }

  .item {
    margin-top: 10px;
    margin-right: 40px;

  }
}

::v-deep .el-badge__content {
    background-color: #fffefd;
    border: 1px solid #b7adbb;
    color: #b7adbb;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    font-size: 1px;
    // text-align: center;
    line-height: 14px;
  }
</style>
